package com.java.framework.utils;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.google.common.collect.Lists;

/** 
 * 定义一个查询条件容器 
 * @author sunshine 
 * 
 * @param <T> 
 */
public class Criteria<T> implements Criterion<T> {
	
	private List<Criterion<T>> criterions = Lists.newArrayList();
	
	/** 
     * 增加简单条件表达式 
     * @Methods add 
     * @Create In 2012-10-12 By sunshine 
     * @param criterion 
     */  
    public void add(Criterion<T> criterion){
        if(criterion!=null){
            criterions.add(criterion);
        }
    }

    /**
     * 将所有条件用 and 联合起来
     */
	@Override
	public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
		// TODO Auto-generated method stub
		if(!criterions.isEmpty()){
			List<Predicate> predicates = Lists.newArrayList();
			for(Criterion<T> c : criterions){
				predicates.add(c.toPredicate(root, query, cb));
			}
			if(predicates.size() > 0){
				return cb.and(predicates.toArray(new Predicate[predicates.size()]));
			}
		}
		return cb.conjunction();
	}

}
